package PowerWord.Core.Plan;

import java.util.Random;

import PowerWord.Core.Data.FullInfo;

public class SingleExercise extends Exercise {
	
	ExerciseData[] datas = null;
	
	public static int OptionSize = 4;
	class ExerciseData{
		FullInfo[] items = new FullInfo[OptionSize];
		int answer = -1;
	}
	
	public SingleExercise(int groupSize) {
		super(groupSize);
		datas = new ExerciseData[GroupFullSize];
	}
	
	public String GetQuestion(boolean mode, int index){
		ExerciseData data = datas[index];
		return mode ? data.items[data.answer].word : data.items[data.answer].data.GetSimpContent();
	}
	
	public String GetOption(boolean mode, int index, int id){
		ExerciseData data = datas[index];
		return mode ? data.items[id].data.GetSimpContent() : data.items[id].word;
	}
	
	public int GetAnswer(int index){
		return datas[index].answer;
	}
	
	public void SaveScore(int index, int usrAnswer){
		if(usrAnswer == datas[index].answer){
			++score;
		}
		else{
			AddWrongWord(index);
		}
	}
	
	private int GetRandomItems(int skip, int max, int[] poses){
		Random seed = new Random();
		poses[0] = skip;
		for(int i=1; i<poses.length; ++i){
			int p = seed.nextInt(max-i);
			int steps = 0;
			for(int j=0; j<i; ++j){
				steps += poses[j] > p ? 0 : 1;
			}
			poses[i] = p + steps;
		}
		int answer = new Random().nextInt(OptionSize);
		poses[0] = poses[answer];
		poses[answer] = skip;
		return answer;
	}
	
	public void Prepare(){
		int basePos = curGroup * GroupFullSize;
		int groupSize = GetCurGroupSize();
		int[] poses = new int[OptionSize];
		for(int i=0; i<groupSize; ++i){
			datas[i] = new ExerciseData();
			datas[i].answer = GetRandomItems(basePos+i, mDuty.GetCount(), poses);
			for(int j=0; j<OptionSize; ++j){
				datas[i].items[j] = Controller.Instance().GetFullInfo(poses[j]);
			}
		}
	}
}
